from django.core.cache import cache
from django.http import JsonResponse
from urllib.parse import quote, unquote
import requests
from django.db import connection

"""
    100                       私聊消息
    200                       群聊消息
"""


def send_msg(msg_type, msg, to_wxid, at_wxid='', at_name=''):
    """
    机器人发送消息

    :param  string $to_wxid 群id
    :param  int $msg_type 100普通消息，102群at某人
    :param  string $at_wxid 艾特的id，群成员的id
    :param  string $at_name 艾特的昵称，群成员的昵称
    :param  string $msg     消息内容
    :return string json_string

    """

    # msg_type = int(request.GET.get("type"))
    # msg = request.GET.get("msg")
    # to_wxid = request.GET.get("to_wxid")
    # at_wxid = request.GET.get("at_wxid")
    # at_name = request.GET.get("at_name")

    response = requests.post(
        url='http://119.29.55.73:8073/send',
        json={
            "type": msg_type,
            "msg": quote(msg, 'utf-8'),
            "to_wxid": to_wxid,
            "at_wxid": at_wxid,
            "at_name": at_name,
            "robot_wxid": "wxid_tlk9crt41e7s22"
        }
    )
    return JsonResponse(response.json(), safe=False)


def query_all_dict(sql, params=None):
    """
    查询所有结果集返回字典类型数据

    :rtype: object
    :param sql:
    :param params:
    :return:
    """
    with connection.cursor() as cursor:
        if params:
            cursor.execute(sql, params=params)
        else:
            cursor.execute(sql)
        col_names = [desc[0] for desc in cursor.description]
        row = cursor.fetchall()
        rowList = []
        for list in row:
            tMap = dict(zip(col_names, list))
            rowList.append(tMap)
        return rowList


def query_one_dict(sql, params=None):
    """
    查询一个结果返回字典类型数据
    :param sql:
    :param params:
    :return:
    """
    with connection.cursor() as cursor:
        if params:
            cursor.execute(sql, params=params)
        else:
            cursor.execute(sql)
        col_names = [desc[0] for desc in cursor.description]
        row = cursor.fetchone()
        tMap = dict(zip(col_names, row))
        return tMap


def book_list(sql: str):
    """
    执行原生SQL

    :param sql:
    :return:
    """
    # 真正的原生sql,
    cursor = connection.cursor()
    cursor.execute(f"{sql}")
    raw = cursor.fetchall()
    return raw


def get_checkCount(stu_card: str, incr: bool = False) -> int:
    """
    获取累计打卡的次数

    :return:
    """
    count = 0
    if cache.has_key(f'user:{stu_card}:count'):
        # 如果缓存中已经有数据
        count = cache.get(f'user:{stu_card}:count')
    else:
        try:
            data = query_one_dict(f"\n"
                                  f"            SELECT * \n"
                                  f"            FROM check_count \n"
                                  f"            WHERE stu_card={stu_card}\n"
                                  f"            ")
            count = data['count']
            cache.set(f'user:{stu_card}:count', count, timeout=None)
        except:
            count = 0
    if incr:
        # 如果需要自增
        count = cache.incr(f'user:{stu_card}:count', 1)  # 累计打卡次数+1

    return count
